<template>
  <n-card :bordered="false" class="proCard">
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="tableActionRef"
      :actionColumn="tableActionColumn"
      :scroll-x="920"
    >
      <template #tableTitle>
        <n-button type="primary" @click="() => {
            optionModelDetail.type = 0;
            optionModelDetail.show = true;
            formParam.configKey = formParam.configName = formParam.configValue = formParam.remark = '';
          }">
          添加系统配置
        </n-button>
      </template>

      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal
      v-model:show="optionModelDetail.show"
      style="width: 400px"
      preset="card"
      :title="optionModelDetail.title[optionModelDetail.type]"
      size="medium"
      :bordered="false"
    >
      <n-form
        ref="formRef"
        label-placement="left"
        size="large"
        :model="formParam"
        :rules="rules"
      >
        <n-form-item path="configName">
          <n-input-group>
            <n-input-group-label style="height: 42px; line-height: 42px">名称</n-input-group-label>
            <n-input :maxlength="20" show-count v-model:value="formParam.configName" placeholder="请输入名称" />
          </n-input-group>
        </n-form-item>
        <n-form-item path="configKey">
          <n-input-group>
            <n-input-group-label style="height: 42px; line-height: 42px">键名</n-input-group-label>
            <n-input :maxlength="128" show-count v-model:value="formParam.configKey" placeholder="请输入键名" :disabled="!!optionModelDetail.type" />
          </n-input-group>
        </n-form-item>
        <n-form-item path="configValue">
          <n-input-group>
            <n-input-group-label style="height: 42px; line-height: 42px">键值</n-input-group-label>
            <n-input :maxlength="512" show-count v-model:value="formParam.configValue" placeholder="请输入键值" />
          </n-input-group>
        </n-form-item>
        <n-form-item path="remark">
          <n-input-group>
            <n-input-group-label style="height: 42px; line-height: 42px">备注</n-input-group-label>
            <n-input type="textarea"
                     v-model:value="formParam.remark" placeholder="请输入备注"
                     :autosize="{ minRows: 1, maxRows: 5 }"
                     maxlength="128" show-count
            />
          </n-input-group>
        </n-form-item>
        <n-form-item>
          <n-button type="primary" @click="handleSubmit" size="large" :loading="loading" block>
            {{ optionModelDetail.title[optionModelDetail.type] }}
          </n-button>
        </n-form-item>
      </n-form>
    </n-modal>

  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { useMessage, NButton, useDialog } from "naive-ui";
import { columns } from "@/views/system/config/columns";
import { BasicTable, TableAction } from '@/components/Table';
import { getConfigPage, addConfig, updateConfig, deleteConfig } from "@/api/system/config";
import { useUserStore } from "@/store/modules/user";
import { useGlobSetting } from "@/hooks/setting";
import { ResultEnum } from "@/enums/httpEnum";
import { EditOutlined } from '@vicons/antd'
import { Trash } from '@vicons/ionicons5'

const global = useGlobSetting()
const userStore = useUserStore()
const message = useMessage()
const dialog = useDialog()

const tableActionRef = ref();
const tableActionColumn = reactive({
  width: 150,
  title: '操作',
  key: 'action',
  fixed: 'right',
  align: 'center',
  render(row) {
    return h(TableAction, {
      style: 'text',
      actions: [
        {
          label: '编辑',
          icon: EditOutlined,
          onClick: () => {
            formParam.id = row.id
            formParam.configName = row.configName
            formParam.configKey = row.configKey
            formParam.configValue = row.configValue
            formParam.remark = row.remark
            optionModelDetail.type = 1
            optionModelDetail.show = true
          }
        },
        {
          label: '删除',
          type: 'error',
          icon: Trash,
          onClick: () => {
            dialog.warning({
              title: '警告',
              content: '你确定删除该条系统配置？',
              positiveText: '确定',
              negativeText: '取消',
              onPositiveClick: () => {
                deleteConfig(row.id)
                  .then(() => reloadTable())
                  .catch(() => dialog.destroyAll())
              },
              onNegativeClick: () => { }
            })
          }
        },
      ]
    })
  }
});

const loadDataTable = async (res) => {
  const data = await getConfigPage({pageNum: res.current, pageSize: res.size});
  // total 指的是总共多少条数据
  const { current, size, total, records } = data;
  return {
    current,
    size,
    count: Math.ceil(total / size),
    records,
  };
};

function reloadTable() {
  tableActionRef.value.reload();
}

// 修改内容
const optionModelDetail = reactive({
  show: false,
  title: ['添加', '更新'],
  type: 0
})
const loading = ref(false);
const formRef: any = ref(null);
const formParam = reactive({
  id: 0,
  configName: '',
  configKey: '',
  configValue: '',
  remark: ''
})
const rules = {
  configName: { required: true, message: '请输入名称', trigger: 'blur' },
  configKey: { required: true, message: '请输入键名', trigger: 'blur' },
  configValue: { required: true, message: '请输入键值', trigger: 'blur' }
};

const handleSubmit = (e) => {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const { id, configName, configKey, configValue, remark } = formParam;
      loading.value = true;

      try {
        if (optionModelDetail.type === 0) {
          const { code, message: msg } = await addConfig({ configName, configKey, configValue, remark })
          if (code === ResultEnum.SUCCESS) {
            optionModelDetail.show = false
            message.success(msg)
          } else {
            message.warning(msg)
          }
        } else if (optionModelDetail.type === 1) {
          const { code, message: msg } = await updateConfig(id, { configName, configKey, configValue, remark })
          if (code === ResultEnum.SUCCESS) {
            optionModelDetail.show = false
            message.success(msg)
          } else {
            message.warning(msg)
          }
        }
        reloadTable()
      } finally {
        loading.value = false;
      }
    } else {
      message.error('请填写完整信息');
    }
  });
};


</script>

<style lang="less" scoped>
:deep(.my-icon .n-button__icon) {
  margin: 0 !important;
}
</style>
